const http = require('http')
const mysql = require('mysql')
const fs = require('fs')
const path = require('path')

http.createServer((req, res) => {
    console.log(req.url)
    if (req.url == '/') {
        var filePath = path.join(__dirname, '/chapterList.html')
        var fileContent = fs.readFileSync(filePath)
        res.writeHead(200, { "Content-Type": "text/html" })
        res.write(fileContent)
        res.end()
    } else if (req.url == '/getChapterList') {
        // 获取图片名字
        var filePath = path.join(__dirname, '/images')
        var files = fs.readdirSync(filePath)

        // 数据库操作
        var con = mysql.createConnection({
            host: '192.168.187.144',
            port: 3306,
            user: 'root',
            password: 'ddd',
            database: 'mydatabase'
        })
        var selectSql = 'select * from chapters'

        var chapterlist = []
        con.query(selectSql, (err, result) => {
            // 回调函数异步执行，必须把响应内容写在回调函数里面，否则得到数组仍然是那个空数组
            if (err) {
                console.log(err)
            } else {
                console.log(result)
                for (var i = 0; i < result.length; i++) {
                    console.log(result[i]['chapterName'])
                    chapterlist[i] = {
                        chapterName: result[i]['chapterName'],
                        imgPath: 'images/'+files[i],
                        chapterDes: result[i]['chapterDes'],
                        publishTimer: result[i]['publishTimer'],
                        author: result[i]['author'],
                        views: result[i]['views'],
                        chapterId:i
                    }
                }
                var chapterList = JSON.stringify(chapterlist)
                console.log(chapterList)
                res.writeHead(200, { "Content-Type": "text/plain" })
                res.write(chapterList)
                res.end()
            }
        })

    } else if (req.url.indexOf('css/') >= 0) {
        var filePath = path.join(__dirname, '/'+req.url)
        var fileContent = fs.readFileSync(filePath)
        res.writeHead(200, { "Content-Type": "text/css" })
        res.write(fileContent)
        res.end()
    } 
     else if (req.url.indexOf('/baiduTemplate.js') >= 0) {
        var filePath = path.join(__dirname, '/js/baiduTemplate.js')
        var fileContent = fs.readFileSync(filePath)
        res.writeHead(200, { "Content-Type": "text/js" })
        res.write(fileContent)
        res.end()
    } else if (req.url.indexOf('images/') >= 0) {
        var imgPath = path.join(__dirname, '/' + req.url)
        var imgContent = fs.readFileSync(imgPath)
        res.writeHead(200, { "Content-Type": "image/jpg" })
        res.write(imgContent)
        res.end()
    }else if(req.url.indexOf('/getDetail')>=0){
        var con = mysql.createConnection({
            host: '192.168.187.144',
            port: 3306,
            user: 'root',
            password: 'ddd',
            database: 'mydatabase'
        })
        var selectSql = 'select * from chaptersDetail where chapterId=?'

        
        var arr=req.url.split('=')
        var chapterId=arr[1]

        var chapterdetail = []
        con.query(selectSql,[chapterId], (err, result) => {
            // 回调函数异步执行，必须把响应内容写在回调函数里面，否则得到数组仍然是那个空数组
            if (err) {
                console.log(err)
            } else {
                console.log(result)
                for (var i = 0; i < result.length; i++) {
                    console.log(result[i]['chapterName'])
                    chapterdetail[i] = {
                        chapterId:result[i]['chapterId'],
                        chapterName: result[i]['chapterName'],
                        publishTimer: result[i]['publishTimer'],
                        author: result[i]['author'],
                        views: result[i]['views'],
                        chapterContent: result[i]['chapterContent']
                    }
                }
                var chapterDetail = JSON.stringify(chapterdetail)
                console.log(chapterDetail)
                // 解决跨域问题（从8084端口响应到8083端口，发送请求不会产生跨域，但是响应数据会产生跨域）
                res.setHeader("Access-Control-Allow-Origin","*")
                res.writeHead(200, { "Content-Type": "text/plain" })
                res.write(chapterDetail)
                res.end()
            }
        })
    }

}).listen(8084)